package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zg3/developer-branch/api/request"
	"zg3/developer-branch/internal/dao"
	"zg3/developer-branch/internal/model"
)

func CreateRoom(c *gin.Context) {
	var req request.CreateRoomReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	chatRoom := model.ChatRoom{
		UserId: c.GetUint("userId"),
		Title:  req.Title,
	}
	if !dao.Create(&chatRoom) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "创建聊天室失败",
			"data": false,
		})
		return
	}
	chatRoomUser := model.ChatRoomUser{
		ChatRoomId: chatRoom.Id,
		UserId:     chatRoom.UserId,
		Position:   2,
	}
	dao.Create(&chatRoomUser)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "创建聊天室成功",
		"data": chatRoom,
	})
	return
}

func AddRoomUser(c *gin.Context) {
	var req request.AddRoomUserReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}

	var chatRoom model.ChatRoom
	dao.QueryId(req.ChatRoomId, &chatRoom)
	if chatRoom.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "聊天室不存在",
			"data": false,
		})
		return
	}
	var chatRoomUser model.ChatRoomUser

	dao.ConditionQuery(&model.ChatRoomUser{
		ChatRoomId: req.ChatRoomId,
		UserId:     c.GetUint("userId"),
	}, &chatRoomUser)

	if chatRoomUser.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "已经在聊天室",
			"data": chatRoomUser,
		})
		return
	} else {
		newChatRoomUser := model.ChatRoomUser{
			ChatRoomId: req.ChatRoomId,
			UserId:     c.GetUint("userId"),
			Position:   0,
		}
		dao.Create(&newChatRoomUser)

		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "进入聊天室成功",
			"data": newChatRoomUser,
		})
		return
	}
}
